//
//  DeviceListViewController.m
//  IPTV
//
//  Created by Echo on 14-4-2.
//  Copyright (c) 2014年 Echo. All rights reserved.
//

#import "DeviceListViewController.h"
#import "TVViewController.h"
#import "PokerControlClient.h"
#import "RemoteControlClient.h"
#import "DDAlertPrompt.h"

@interface DeviceListViewController ()

@end

@implementation DeviceListViewController
@synthesize TableView1, udpSocket;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)stopUdpData{
    NSLog(@"停止发送udp包");
    isStopUdpData = YES;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self stopUdpData];
}
-(void)sendUdpData{
    if (!isStopUdpData) {
        int port = 15002;
        if (!self.udpSocket) {
            self.udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
            NSError *error = nil;
            [self.udpSocket enableBroadcast:YES error:&error];
            if (![self.udpSocket bindToPort:port error:&error])
            {
                NSLog(@"bindToPort error");
            }
        }
        [self.udpSocket receiveWithTimeout:-1 tag:0];
        NSString *sentip = @"255.255.255.255";
        NSString *dataStr = @"IFOProbeDevice";
        NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"device list SEND TO : %@:%d    %@", sentip, port, dataStr);
        [self.udpSocket sendData:data toHost:sentip port:port withTimeout:-1 tag:0];
        [self performSelector:@selector(sendUdpData) withObject:nil afterDelay:.5];
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
//    [dic setObject:@"192.168.1.105" forKey:@"R0026290305a2"];
//    [dic setObject:@"192.168.1.106" forKey:@"R0026290305a3"];
//    [dic setObject:@"192.168.1.107" forKey:@"R002629030502"];
//    [dic setObject:@"192.168.1.108" forKey:@"R002629030806"];
//    [dic setObject:@"192.168.1.109" forKey:@"002629030800"];
//    [UD setObject:dic forKey:LANIPAddress_list];
//    [UD synchronize];
    
    netConnectSucList = [[NSMutableArray alloc] init];
    dicList = [[NSMutableDictionary alloc] init];
    [dicList setDictionary:[UD objectForKey:LANIPAddress_list]];
    
    self.title = STR(@"智能遥控列表");
    if ([Global curLanguageEn]) {
        self.title = @"WIFI Smart IR Controller List";
    }
    
    self.TableView1 = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-44-20) style:UITableViewStylePlain];
    self.TableView1.backgroundColor = [UIColor clearColor];
    self.TableView1.delegate = self;
    self.TableView1.dataSource = self;
    self.TableView1.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.TableView1];
    
    [[PokerControlClient share].curIpList removeAllObjects];
    [NC addObserver:self selector:@selector(connectWIFI) name:StopUdpData object:nil];
    [self performSelector:@selector(connectDeviceList) withObject:nil afterDelay:1];
    isStopUdpData = NO;
    [self sendUdpData];
}
-(void)connectDeviceList{
    if ([PokerControlClient share].curIpList.count == 0) {
        if (dicList.count > 0){
            [NC addObserver:self selector:@selector(remoteNetConnectSuc) name:CONNECT_SUC_REMOTE object:nil];
            [[RemoteControlClient share] openStream];
        }
    }
}
-(void)connectWIFI{
    m_isRemote = NO;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(connectDeviceList) object:nil];
    [TableView1 reloadData];
}
-(void)remoteDeviceName:(NSNotification*)noti{
    NSLog(@"remoteDeviceName : %@", noti.object);
//    [NC removeObserver:self name:StopUdpData object:nil];
//    [self stopUdpData];
    NSString *str = noti.object;
    [netConnectSucList addObject:str];
    m_isRemote = YES;
    [TableView1 reloadData];
}
-(void)remoteNetConnectSuc{
    [NC addObserver:self selector:@selector(remoteDeviceName:) name:REMOTE_DEVICE_NAME object:nil];
    for (int i=0; i<[dicList allKeys].count; i++) {
        NSString *name = [[dicList allKeys] objectAtIndex:i];//0026290305a2
        NSString *string = [NSString stringWithFormat:@"[%@]", name];
        NSLog(@"stringname : %@", string);
        [[RemoteControlClient share] startRemoteCmd:0x10 sec:0x03 dataStr:string];//获取设备是否在线
    }
}
-(void)dealloc{
    NSLog(@"");
    [[RemoteControlClient share] disConnect];
    [NC removeObserver:self];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dicList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 64;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"TableView1Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 62)];
    bg.backgroundColor = [UIColor whiteColor];
    [cell addSubview:bg];
    
    UIImageView *logo = [[UIImageView alloc] initWithImage:IMG(@"control_logo.png")];
    logo.frame = CGRectMake(1.5+8, 9.5, 66-8*2, 43);
    [cell addSubview:logo];
    
    GoodLabel *nameLabel = [GoodLabel labelWithFont:14 title:STR(@"")];
    nameLabel.textAlignment = UITextAlignmentCenter;
    nameLabel.text = STR(@"Wi-Fi智能红外遥控器");
    if ([Global curLanguageEn]) {
        nameLabel.text = @"Smart IR Control";
    }
    
    nameLabel.textColor = [UIColor blackColor];
    nameLabel.frame = CGRectMake(85, 10, kScreenWidth/2, 20);
    [cell addSubview:nameLabel];
    NSString *device_name = nil;
    if ([dicList allKeys].count > indexPath.row) {
        device_name = [[dicList allKeys] objectAtIndex:indexPath.row];
        GoodLabel *deviceLabel = [GoodLabel labelWithFont:12 title:device_name];
        deviceLabel.textAlignment = UITextAlignmentCenter;
        deviceLabel.textColor = [UIColor blackColor];
        deviceLabel.frame = CGRectMake(FX(nameLabel), 30+5, kScreenWidth/2, 20);
        [cell addSubview:deviceLabel];
        
        NSDictionary *dicNameList = [UD objectForKey:LAN_Remote_Name_list];
        NSString *UserDeviceName = [dicNameList objectForKey:device_name];
        if ([UserDeviceName length] > 0) {
            nameLabel.text = UserDeviceName;
        }
    }
    
    UIImage *stateImage = IMG(@"offline.png");
    if ([Global curLanguageEn]) {
        stateImage = IMG(@"offline_en.png");
    }
    
    if (dicList.count > indexPath.row) {
        NSString *curDevice = [[dicList allKeys] objectAtIndex:indexPath.row];
        for (NSString *savaDevice in [[PokerControlClient share].curIpList allKeys]) {
            if ([savaDevice isEqualToString:curDevice]) {
                stateImage = IMG(@"share.png");
                break;
            }
        }
    }
    
    BOOL connect = NO;
    for (NSString *name in netConnectSucList) {
        if ([name isEqualToString:device_name]) {
            connect = YES;
            break;
        }
    }
    if (connect) {
        stateImage = IMG(@"share.png");
        if (m_isRemote) {
            stateImage = IMG(@"wan_online.png");
        }
    }
    
    UIImageView *state = [[UIImageView alloc] initWithImage:stateImage];
    state.frame = CGRectMake(kScreenWidth-stateImage.size.width/2-5, (62-stateImage.size.height/2)/2, stateImage.size.width/2, stateImage.size.height/2);
    if (FW(state) < 30) {
        float scale = .75;
        state.frame = CGRectMake(kScreenWidth-stateImage.size.width*scale-5, (62-stateImage.size.height*scale)/2, stateImage.size.width*scale, stateImage.size.height*scale);
    }
    [cell addSubview:state];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
-(void)setDiveceNameInfo:(NSIndexPath *)indexPath {
    NSString *device_name = nil;
    if ([dicList allKeys].count > indexPath.row) {
        device_name = [[dicList allKeys] objectAtIndex:indexPath.row];
    }
    if ([device_name length] > 1) {
        [PokerControlClient share].net_deviceName = device_name;
    }
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
	if (dicList.count>0) {
		return UITableViewCellEditingStyleDelete;
	}else {
		return UITableViewCellEditingStyleNone;
	}
}

#pragma mark -
#pragma mark Table View Data Source Methods
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *device_name = nil;
    if ([dicList allKeys].count > indexPath.row) {
        device_name = [[dicList allKeys] objectAtIndex:indexPath.row];
        [dicList removeObjectForKey:device_name];
    }
    [UD setObject:dicList forKey:LANIPAddress_list];
    [UD synchronize];
    
    if ([dicList count] == 0) {
        [tableView reloadData];
    } else {
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [PokerControlClient share].isRemote = NO;
    
    [self setDiveceNameInfo:indexPath];
//    m_isRemote = YES;
    if (m_isRemote) {
        NSString *device_name = nil;
        if ([dicList allKeys].count > indexPath.row) {
            device_name = [[dicList allKeys] objectAtIndex:indexPath.row];
        }
        BOOL connect = NO;
        for (NSString *name in netConnectSucList) {
            if ([name isEqualToString:device_name]) {
                connect = YES;
                break;
            }
        }
//        connect = YES;
        if (connect) {
            [PokerControlClient share].isRemote = YES;
            [PokerControlClient share].net_deviceName = device_name;
            [self enterNextView];
        }
    }else{
        connectIndex = indexPath.row;
        if (dicList.count > indexPath.row) {
            
            [PokerControlClient share].ctrlIP = @"192.168.1.106";//test
            [self enterNextView];//test
//            NSString *curDevice = [[dicList allKeys] objectAtIndex:indexPath.row];
//            for (int i=0; i<[[PokerControlClient share].curIpList allKeys].count; i++) {
//                NSString *savaDevice = [[[PokerControlClient share].curIpList allKeys] objectAtIndex:i];
//                NSString *savaIP = [[[PokerControlClient share].curIpList allValues] objectAtIndex:i];
//                if ([savaDevice isEqualToString:curDevice]) {
//                    [PokerControlClient share].ctrlIP = savaIP;
//                    [self enterNextView];
//                    break;
//                }
//            }
        }
    }
}
-(void)enterNextView{
    [[PokerControlClient share] stopc2sPing];
    [NC removeObserver:self];
    
    if ([DataManager GetInstance:[PokerControlClient share].net_deviceName].deviceArray.count > 0) {
        TVViewController *studyView = [[TVViewController alloc] init];
        [self.navigationController pushViewController:studyView animated:YES];
    }else{
        TVViewController *studyView = [[TVViewController alloc] init];
        [self.navigationController pushViewController:studyView animated:NO];
    }
}

//允许长按菜单
-(BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"xxx");
    tableview_select_index = indexPath.row;
    //    [tableview reloadData];
    
    UIActionSheet *sheet = nil;
    if ([Global curLanguageEn]) {
        sheet = [[UIActionSheet alloc] initWithTitle:@"Select" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Modify the device info", nil];
        sheet.tag = modify_device_tag;
        [sheet showInView:self.view];
    }else{
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择操作" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"修改设备信息", nil];
        sheet.tag = modify_device_tag;
        [sheet showInView:self.view];
    }
    return NO;
}
-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender{
    return NO;
}
-(BOOL)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender{
    if (action==@selector(copy:)) {
        return YES;
    }
    return NO;
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        DDAlertPrompt *loginPrompt = nil;
        if ([Global curLanguageEn]){
            loginPrompt = [[DDAlertPrompt alloc] initWithTitle:@"Input the device name" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitle:@"OK" content:@""];
            loginPrompt.tag = 23;
            [loginPrompt show];
        }else{
            loginPrompt = [[DDAlertPrompt alloc] initWithTitle:@"请输入设备名称" delegate:self cancelButtonTitle:@"取消" otherButtonTitle:@"确定" content:@""];
            loginPrompt.tag = 23;
            [loginPrompt show];
        }
    }
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
	if (buttonIndex != [alertView cancelButtonIndex])
    {
        DDAlertPrompt *loginPrompt = (DDAlertPrompt *)alertView;
        NSString *groupName = loginPrompt.plainTextField.text;
        if ([groupName length] > 0) {
            NSString *curDevice = [[dicList allKeys] objectAtIndex:tableview_select_index];
            
            NSDictionary *dicNameList = [UD objectForKey:LAN_Remote_Name_list];
            NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:dicNameList];
            [dic setObject:groupName forKey:curDevice];
            [UD setObject:dic forKey:LAN_Remote_Name_list];
            [UD synchronize];
            [TableView1 reloadData];
        }
	}
}

@end
